package com.jumeng.util;

import com.github.wxpay.sdk.WXPay;
import com.github.wxpay.sdk.WXPayUtil;
import com.jumeng.server.impl.WXPayConfigImpl;
import lombok.extern.slf4j.Slf4j;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;
import java.util.SortedMap;
import java.util.TreeMap;

@Slf4j
public class H5WeChatPayUtil {
    /**
     * h5微信支付
     *
     * @Author hehaotian
     * @Param * appId: 公众账号ID
     * @Param * mchId: 商户号
     * @Param * key: 用户私钥
     * @Param orderNo: 订单号
     * @Param money: 金额
     * @Param body: 描述内容
     * @Param openId: 用户标识
     */
    public static Map<String, String> h5WeChatPay(String appId, String machId, String key, String orderNo, String money, String body, String callBack, String openId) {
        WXPayConfigImpl config;
        try {
            config = WXPayConfigImpl.getInstance(appId, machId, key);
            WXPay wxPay = new WXPay(config);
            HashMap<String, String> data = new HashMap<>();
            data.put("body", body);
            data.put("out_trade_no", orderNo);
            data.put("fee_type", "CNY"); //货币设置 CNY:人名币
            data.put("total_fee", money); //标价金额
            data.put("spbill_create_ip", ""); //终端IP
            //notify_url body 异步接收微信支付结果通知的回调地址，通知url必须为外网可访问的url，不能携带参数。 公网域名必须为https，如果是走专线接入，使用专线NAT IP或者私有回调域名可使用http
            // 回调地址
            data.put("notify_url", callBack); //通知地址
            data.put("trade_type", "MWEB");
            // System.out.println("当前openid========"+openId);
            data.put("openid", openId);

            Map<String, String> r = wxPay.unifiedOrder(data);
            if ("SUCCESS".equals(r.get("return_code")) && "OK".equals(r.get("return_msg"))) {
                Map<String, String> map = new HashMap<String, String>();
                map.put("appId", config.getAppID());
                map.put("package", "prepay_id=" + r.get("prepay_id"));
                map.put("nonceStr", WXPayUtil.generateNonceStr());
                map.put("signType", "MD5");
                map.put("timeStamp", (System.currentTimeMillis() / 1000) + "");
                map.put("sign", WXPayUtil.generateSignature(map, config.getKey()));
                map.put("code_url",r.get("code_url"));
                return new HashMap<String, String>() {
                    private static final long serialVersionUID = 1L;

                    {
                        putAll(map);
                    }
                };
            } else {
                return r;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
}
